package blms.services.internal;

import blms.domain.Matchup;
import blms.exception.RestrictionException;
import blms.repository.MatchupTableRepository;
import blms.services.MatchupService;
import blms.util.BLMSMessages;

/**
 * Default implementation of <code>MatchupService</code>
 * 
 */
public class MatchupServiceImpl implements MatchupService {
	
	private final MatchupTableRepository matchups;

	/**
	 * @param matchups
	 */
	public MatchupServiceImpl(MatchupTableRepository matchups) {
		this.matchups = matchups;
	}

	/* (non-Javadoc)
	 * @see blms.services.MatchupService#createMatchup(int, int, java.lang.String)
	 */
	public Matchup createMatchup(int handicapStronger, int handicapWeaker,
			String scoreHigherRatedPlayer) throws RestrictionException {
		
		int scoreHigherRatedPlayerInt;
		try {
			scoreHigherRatedPlayerInt = Integer.parseInt(scoreHigherRatedPlayer);
		} catch (NumberFormatException e) {
			throw new RestrictionException(BLMSMessages.TABLE_MUST_BE_AN_INTEGER_MESSAGE);
		}
		
		if (!this.matchups.containsTable(scoreHigherRatedPlayerInt)) throw new RestrictionException(BLMSMessages.UNKNOWN_TABLE_MESSAGE);
		
		if (handicapStronger < 0 || handicapWeaker < 0) throw new RestrictionException(BLMSMessages.HANDICAP_MUST_BE_POSITIVE_MESSAGE);
		if (handicapWeaker > handicapStronger) throw new RestrictionException(BLMSMessages.HANDICAP_WEAKER_GREATER_HANDICAP_STRONGER_MESSAGE);
		
		int result = this.matchups.getValueFor(handicapStronger - handicapWeaker, scoreHigherRatedPlayerInt);
		
		return new Matchup(handicapStronger, handicapWeaker, scoreHigherRatedPlayerInt, result);
	}
}
